#include "adc_driver.h"
adc_oneshot_unit_handle_t adc_handle;
adc_oneshot_unit_init_cfg_t init_config;
adc_cali_handle_t adc1_cali_chan0_handle = NULL;
bool do_calibration1_chan0;
const static char *TAG = "adc_driver";

/*---------------------------------------------------------------
        ADC Calibration
---------------------------------------------------------------*/
static bool example_adc_calibration_init(adc_unit_t unit, adc_channel_t channel, adc_atten_t atten, adc_cali_handle_t *out_handle)
{
    adc_cali_handle_t handle = NULL;
    esp_err_t ret = ESP_FAIL;
    bool calibrated = false;

#if ADC_CALI_SCHEME_CURVE_FITTING_SUPPORTED
    if (!calibrated) {
        ESP_LOGI(TAG, "calibration scheme version is %s", "Curve Fitting");
        adc_cali_curve_fitting_config_t cali_config = {
            .unit_id = unit,
            .chan = channel,
            .atten = atten,
            .bitwidth = ADC_BITWIDTH_DEFAULT,
        };
        ret = adc_cali_create_scheme_curve_fitting(&cali_config, &handle);
        if (ret == ESP_OK) {
            calibrated = true;
        }
    }
#endif

#if ADC_CALI_SCHEME_LINE_FITTING_SUPPORTED
    if (!calibrated) {
        ESP_LOGI(TAG, "calibration scheme version is %s", "Line Fitting");
        adc_cali_line_fitting_config_t cali_config = {
            .unit_id = unit,
            .atten = atten,
            .bitwidth = ADC_BITWIDTH_DEFAULT,
        };
        ret = adc_cali_create_scheme_line_fitting(&cali_config, &handle);
        if (ret == ESP_OK) {
            calibrated = true;
        }
    }
#endif

    *out_handle = handle;
    if (ret == ESP_OK) {
        ESP_LOGI(TAG, "Calibration Success");
    } else if (ret == ESP_ERR_NOT_SUPPORTED || !calibrated) {
        ESP_LOGW(TAG, "eFuse not burnt, skip software calibration");
    } else {
        ESP_LOGE(TAG, "Invalid arg or no memory");
    }

    return calibrated;
}



void device_adc_init(uint8_t adc, uint8_t channel)
{

    adc_oneshot_new_unit(&init_config, &adc_handle);
    init_config.unit_id = adc;
    //-------------ADC1 Config---------------//
    adc_oneshot_chan_cfg_t config = {
        .bitwidth = ADC_BITWIDTH_DEFAULT,
        .atten = EXAMPLE_ADC_ATTEN,
    };
    
    adc_oneshot_config_channel(adc_handle, channel, &config);
    
    do_calibration1_chan0 = example_adc_calibration_init(adc, channel, EXAMPLE_ADC_ATTEN, &adc1_cali_chan0_handle);
}


int device_adc_read(uint8_t channel)
{
    uint32_t adc_data_value = 0;
    int adc_data=0;
    int voltage=0;

    /* 采样64次取平均 */
    for (int i = 0; i < NO_OF_SAMPLES; i++) 
    {
       adc_oneshot_read(adc_handle, channel, &adc_data);
       adc_data_value += adc_data;
    }
    adc_data_value /= NO_OF_SAMPLES;
    if (do_calibration1_chan0)
    {
        adc_cali_raw_to_voltage(adc1_cali_chan0_handle, adc_data_value, &voltage);
        return voltage;
    }
    else
    {
        return 0;
    }
}


